//
// Created by wayne on 18-12-1.
//

#ifndef ENGINE_RACE_CONSTANTS_H
#define ENGINE_RACE_CONSTANTS_H

#include <tgmath.h>
#include <byteswap.h>
#include <chrono>
#include <fcntl.h>

#define unlikely(x) __builtin_expect(!!(x), 0)

using namespace std;
using namespace std::chrono;

namespace polar_race {

    milliseconds now() {
        return duration_cast<milliseconds>(system_clock::now().time_since_epoch());
    }

    static int KeyLogTotalNum = 2048;
    static int KeyManagerNum = 64;
    static int CacheNumber = 8;
    static int CacheSegmentCount = 2;
    static int CacheThreadNumber = 2;
    static int KeyLogPerManagerNum = KeyLogTotalNum / KeyManagerNum;
    static int KeyRightShiftNum = 64 - (int) std::round(log2(KeyLogTotalNum));
    static size_t PerCacheSize = static_cast<size_t>(256L * 1024 * 1024 * 1024 / KeyLogTotalNum);
    static size_t PerPartSize = PerCacheSize / CacheSegmentCount;

    static size_t ValueSize = 4096;
    static int SegmentCount = 4;
    static size_t SegmentSize = static_cast<size_t>(SegmentCount * ValueSize);

    inline void stringToUint64(const char *str, uint64_t *key) {
        *key = bswap_64(*reinterpret_cast<const uint64_t *>(str));
    }

    inline void uint64ToString(uint64_t key, char *str) {
        *reinterpret_cast<uint64_t *>(str) = bswap_64(key);
    }

    int openOrCreateFile(const std::string &path, long size, int mode) {
        auto fd = open(path.c_str(), mode, 0644);
        if(fd < 0) {
            fd = open(path.c_str(), mode | O_CREAT, 0644);
            posix_fallocate(fd, 0, size);
        }
        return fd;
    }

}

#endif //ENGINE_RACE_CONSTANTS_H
